package com.imooc.mq;

import com.imooc.pojo.MqLocalMsgRecord;
import com.imooc.service.MqLocalMsgRecordService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * MQ消息处理助手类
 * @author liansen
 * @create 03-16-16:59
 */
@Component
public class InitResumeMQProducerHandler {

    @Autowired
    private MqLocalMsgRecordService recordService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public static final ThreadLocal<List<String>> msgIdsThreadLocal = new ThreadLocal<>();

    public void saveLocalMsg(String targetExchange, String routingKey, String msgContent){

        MqLocalMsgRecord record = new MqLocalMsgRecord();
        record.setMsgContent(msgContent);
        record.setRoutingKey(routingKey);
        record.setTargetExchange(targetExchange);
        record.setCreateTime(LocalDateTime.now());
        record.setUpdateTime(LocalDateTime.now());

        recordService.save(record);

        List<String> msgIdsList = msgIdsThreadLocal.get();
        if(CollectionUtils.isEmpty(msgIdsList)){
            msgIdsList = new ArrayList<>();
        }
        //每次消息存储在本地表之后，都需要将消息id存储在当前线程中, 事务提交以后可以对其进行检查
        msgIdsList.add(record.getId());
        msgIdsThreadLocal.set(msgIdsList);
    }

    //发送本地消息到mqconvertAndSend
    public void sendAllLocalMsg(){
        List<String> msgIds = msgIdsThreadLocal.get();
        if(CollectionUtils.isEmpty(msgIds)){
            //如果为空，则可能并不是当前业务所需要进行消息发送，直接结束
            return;
        }
        List<MqLocalMsgRecord> mqLocalMsgRecords = recordService.getBaseMapper().selectBatchIds(msgIds);
        for (MqLocalMsgRecord msgRecord : mqLocalMsgRecords){
            rabbitTemplate.convertAndSend(msgRecord.getTargetExchange(),
                                            msgRecord.getRoutingKey(),
                                            msgRecord.getMsgContent() + "," + msgRecord.getId());

        }
    }
}
